﻿using GN.Pay.TradeChannel.DefaultImpl;
using GN.Pay.TradeChannel.Gyb.Response;
using GN.Pay.TradeChannel.ProtocolPay;
using GN.Pay.Utils;
using GN.Pay.Utils.Net.Http;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;

namespace GN.Pay.TradeChannel.Gyb.Request
{
    [Serializable]
    class ProtocolPayRequest : APayRequest
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="channel"></param>
        /// <param name="order"></param>
        /// <param name="config"></param>
        public ProtocolPayRequest(ITradeChannel channel,
           IOrderPayApply order,
           IProtocolPayApply potoocolApply,
           GybConfigure config) : base(channel, order, config)
        {
            ExceptionUtils.CheckNotNull(potoocolApply, nameof(potoocolApply));
            this.ProtocolNo = potoocolApply.ProtocolNo;
            this.MercUrl = HttpUtility.UrlEncode(config.PayNotifyUrl, Encoding.UTF8);
        }

        /// <summary>
        /// 
        /// </summary>
        public override string TranAbbr
        {
            get
            {
                return TradeCommand.XPER;
            }
        }


        /// <summary>
        /// 支付交易中，接收交易结果的url，如： http://aaa.bbb.ccc/receive.asp
        /// </summary>
        public string MercUrl { get; set; }


        /// <summary>
        /// 协议号
        /// </summary>
        public string ProtocolNo { get; set; }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public override ITradePayApplyResult Build()
        {
            var plain = BuildPlain();
            Dictionary<string, string> dic = new Dictionary<string, string>();
            dic["transName"] = this.TranAbbr;
            dic["Plain"] = plain;
            dic["Signature"] = SecurityUtils.Sign(Config.ConfigureInfo, plain);

            string requestContent = BuildXML(dic, Config);

            HttpClient client = new HttpClient();
            client.Encoding = Config.Encoding;
            client.ContentType = "text/xml";
            var response = client.PostString(new Uri(Config.GatewayUrl), requestContent);

            ProtocolPayResponse res = new ProtocolPayResponse(response, this.Channel, this.Config);
            if (!res.IsSuccess())
            {
                if (res.ErrorMsg == null)
                {
                    res.ErrorMsg = "未知";
                }
                throw this.Channel.ThrowInterfaceException("付款失败:" + res.ErrorMsg);
            }
            if (!res.SignVeryfy())
            {
                this.Channel.ThrowClientRequestException("验证未通过");
            }
            var result = res.ToPayResult();
            return new TradePayApplyResult("", "", "", TradePayApplyResultCallType.PaySuccess, result);
        }
    }
}
